<template>
	<!-- 组件自身不渲染任何内容，仅提供逻辑 -->
	<view style="display: none;" :prop="playStatus" :change:prop="icyRender.watchPlayStatus">
		<text :prop='url' :change:prop="icyRender.watchUrl"></text>
	</view>
</template>

<script>
	export default {
		name: 'IcyFetcher',
		props: {
			url: { type: String, required: true },
			playStatus: { type: String, required: true },
			interval: { type: Number, default: 180000 },
		},
		methods: {
			updateIcyData(data) {
				this.$emit('update', data);
			},
		},
	};
</script>

<script module="icyRender" lang="renderjs">
	export default {
		mounted() {
			this.icyIntervalId = null;
			this.abortController = null;
		},
		methods: {
			watchUrl(newValue, oldValue) {
				if (this.url !== newValue) {
					console.log('电台地址发生改变了');
					this.abortPrevious();
				}
				this.url = newValue;
			},
			watchPlayStatus(newValue, oldValue, ownerInstance, instance) {
				console.log('watchPlayStatus', newValue, oldValue);
				if (newValue === 'playing' || newValue === 'loading') {
					if (!this.icyIntervalId) {
						this.fetchIcyData();
						const that = this;
						this.icyIntervalId = setInterval(() => {
							that.fetchIcyData();
						}, 3 * 60 * 1000);
					}
				} else {
					if (this.icyIntervalId) {
						clearInterval(this.icyIntervalId);
						this.icyIntervalId = null;
					}
				}
			},
			async fetchIcyData() {
				const url = this.url;
				if (this.abortController) {
					this.abortController.abort(); // 中止前一个请求
					console.log('终止了上一个请求')
				}
				this.abortController = new AbortController();
				console.log(`fetchIcyData from url:${url}`);

				try {
					const response = await fetch(url, {
						method: "GET",
						headers: { "Icy-MetaData": "1", "User-Agent": "Mozilla/5.0" },
						signal: this.abortController.signal
					});
					// console.log(JSON.stringify(response.headers))
					console.log("电台名称:", response.headers.get("icy-name"));
					console.log("流派:", response.headers.get("icy-genre"));
					console.log("比特率:", response.headers.get("icy-br"));

					const icyMetaIntHeader = response.headers.get("icy-metaint");
					console.log('ICY 元数据间隔:', icyMetaIntHeader);

					const metaint = icyMetaIntHeader ? parseInt(icyMetaIntHeader, 10) : 16000; // 使用获取的 ICY 元数据间隔
					const reader = response.body.getReader();
					let metadata = ""; // 存储元数据信息
					let cover = '';
					let song = '';

					while (true) {
						const { done, value } = await reader.read();
						if (done) break;

						const text = new TextDecoder().decode(value); // 解码流数据
						// 提取元数据长度字节
						const metadataLengthByte = value[metaint]; // 获取元数据长度（1 字节）
						const metadataLength = metadataLengthByte * 16; // 计算元数据字符串长度

						// 提取元数据
						metadata = text.substring(metaint + 1, metaint + 1 + metadataLength);

						const urlMatch = metadata.match(/StreamUrl='([^']*)';/);
						if (urlMatch) {
							try {
								const res = await fetch(urlMatch[1]);
								const json = await res.json();
								console.log('get streamUrl:', json.eventImageUrlSmall);
								cover = json.eventImageUrlSmall;
							} catch (err) {
								console.error('fetch streamUrl error:', err);
							}
						}

						// 解析 StreamTitle（当前播放的歌曲名称）
						const songMatch = metadata.match(/StreamTitle='([^']+)';/);
						if (songMatch) {
							console.log("当前播放的歌曲:", songMatch[1]);
							song = songMatch[1];
							break;
						}
					}
					await reader.cancel();
					console.log('this.$ownerInstance:', this.$ownerInstance);
					if (song) this.$ownerInstance.callMethod('updateIcyData', { song, cover });
				} catch (error) {
					if (error.name === 'AbortError') {
						console.log('ICY 请求被中止');
					} else {
						console.error('获取 ICY 数据失败:', error.message);
					}
				}
			},
			// 当 url 更新或切换电台时，调用此方法清理
			abortPrevious() {
				console.log('abortPrevious')
				if (this.abortController) {
					this.abortController.abort();
					this.abortController = null;
				}
				if (this.icyIntervalId) {
					clearInterval(this.icyIntervalId);
					this.icyIntervalId = null;
				}
			}
		},
	};
</script>